package cn.tfyhyc.springcloud.controller;

import cn.tfyhyc.springcloud.service.PaymentHystrixService;
import com.netflix.hystrix.contrib.javanica.annotation.DefaultProperties;
import com.netflix.hystrix.contrib.javanica.annotation.HystrixCommand;
import com.netflix.hystrix.contrib.javanica.annotation.HystrixProperty;
import com.netflix.hystrix.contrib.javanica.conf.HystrixPropertiesManager;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;

/**
 * @author 头发又黑又长
 * @Date 2022/10/12 9:25
 * @email zwb15083976291@163.com
 */
@RestController
@RequestMapping("/consumer")
@DefaultProperties(defaultFallback = "payment_global_fallback_method") // 配置全局的默认服务降级
public class OrderHystrixController {
    @Resource
    private PaymentHystrixService paymentHystrixService;

    @GetMapping("/payment/hystrix/ok/{id}")
    @HystrixCommand // 使用默认的服务降级方法
    public String paymentInfo_OK(@PathVariable("id") Integer id) {
        String result = paymentHystrixService.paymentInfo_OK(id);
        return result;
    }

    // 特殊定制化的服务降级
    @GetMapping("/payment/hystrix/timeout/{id}")
    @HystrixCommand(fallbackMethod = "paymentInfo_TimeOutHandler",
            commandProperties = {@HystrixProperty(name = HystrixPropertiesManager.EXECUTION_ISOLATION_THREAD_TIMEOUT_IN_MILLISECONDS,
                    value = "1500")})
    public String paymentInfo_TimeOut(@PathVariable("id") Integer id) {
        int xx = id / 0;
        String result = paymentHystrixService.paymentInfo_TimeOut(id);
        return result;
    }

    // 服务降级执行的方法
    String paymentInfo_TimeOutHandler(@PathVariable("id") Integer id) {
        return "我是消费者80,对方支付系统繁忙请1.5秒钟后再试或者自己运行出错请检查自己,o(T--T)o\n";
    }

    // 全局的服务降级方法
    public String payment_global_fallback_method() {
        return "全局的异常处理";
    }


    @HystrixCommand(fallbackMethod = "str_fallbackMethod",
            groupKey = "strGroupCommand",
            commandKey = "strCommand",
            threadPoolKey = "strThreadPool",
            commandProperties = {
                    // 设置隔离策略，THREAD 表示线程池， SEMAPHORE :信号池隔离
                    @HystrixProperty(name = HystrixPropertiesManager.EXECUTION_ISOLATION_STRATEGY, value = "THREAD"),
                    // 当隔离策略悬着型号
                    @HystrixProperty(name = HystrixPropertiesManager.EXECUTION_ISOLATION_STRATEGY, value = "10"),

            }
    )
    public String payment_global_fallback_method02() {
        return null;
    }

}
